<?php

/**
 * tokopedia  
 */
class PlatformAPIClient_Tokopedia extends PlatformAPIClient_Abstract {
    
    /**
     * client
     * @var type 
     */
    private $_client = null;
    
    /**
     * 初始化
     * @param type $option
     */
    public function __construct($option = array()) {
        
        parent::__construct($option);
        
        require_once dirname(dirname(__FILE__)) . '/third-lib/TokopediaClient.php';
        $client = new TokopediaClient();
        $client->appKey = $option['app_key'];
        $client->appSecret = $option['app_secret'];
        if (!empty($option['debug_mode'])) {
            $client->debugMode = true;
        }
        $this->_client = $client;
    }
    
    /**
     * 设置当前要操作的 shop
     * @param type $shopId
     */
    public function setShopId($shopId) {
        
        $this->_option['shop_id'] = $shopId;
    }

    /**
     * 根据条件获取订单列表
     * @param type $conditions
     */
    public function getOrderList($conditions) {
        
        $api = '/v2/order/list';
        // 注意：因为 tokopedia 对参数顺序有要求，此默认值的 key 不能修改（值可以调整）
        $param = array(
            'fs_id' => $this->_option['fs_id'],
            'from_date' => !empty($conditions['from_date']) ? intval($conditions['from_date']) : time() - 2 * 86400,
            'to_date' => !empty($conditions['to_date']) ? intval($conditions['to_date']) : time() + 86400,
            'page' => !empty($conditions['page']) ? intval($conditions['page']) : 1,
            'per_page' => !empty($conditions['per_page']) ? intval($conditions['per_page']) : 10,
//            'status' => 400,
        );
        if (isset($conditions['status'])) {
            $param['status'] = $conditions['status'];
        }
        $url = $api.'?'.http_build_query($param);
        try {
            $resp = $this->_client->call($url);
        } catch (Exception $e) {
            echo 'Exception: ', $e->getMessage(), PHP_EOL;
            exit;
        }
        $resp = json_decode($resp, true);
        return $resp['data'] ? $resp['data'] : [];
    }

    /**
     * 获取指定订单信息
     * 
     * @param type $orderId
     * @return type
     * @throws Exception
     */
    public function getOrder($orderId) {

        $api = "/v2/fs/{$this->_option['fs_id']}/order";
        $param = array(
            'invoice_num' => $orderId,
        );
        $api = $api.'?'.http_build_query($param);
        try {
            $resp = $this->_client->call($api);
        } catch (Exception $e) {
            throw new Exception('get tokopedia order failed: '.$e->getMessage());
        }
        $resp = json_decode($resp, true);
        $order = $resp['data'];
        if (!$order) {
            return [];
        }
        
        // with product summary (sku)
        foreach ($order['order_info']['order_detail'] as &$item) {
            $product = $this->getProductSummary($item['product_id']);
            $item['sku'] = $product['sku'];
        }
        unset($item);

        return $order;
    }
    
    /**
     * 获取指定商品的简要信息
     * @param type $productId
     * @return type
     * @throws Exception
     */
    public function getProductSummary($productId) {
        static $productCache = [];
        
        if (isset($productCache[$productId])) {
            return $productCache[$productId];
        }

        $page = 1;
        $perPage = 1;
        $api = "/v2/products/fs/{$this->_option['fs_id']}/{$page}/{$perPage}?product_id={$productId}";
        try {
            $resp = $this->_client->call($api);
        } catch (Exception $e) {
            throw new Exception('get tokopedia product summary failed: '.$e->getMessage());
        }
        $resp = json_decode($resp, true);
        $products = $resp['data'];
        $productCache[$productId] = $products[0];
        
        return $productCache[$productId];
    }

    /**
     * 设置指定 sku 在平台的库存量
     * @param type $sku
     * @param type $stock
     */
    public function setStock($sku, $stock) {
        
        if (!isset($sku['sku_id'])) {
            throw new Exception('invalid sku info: '.json_encode($sku));
        }
        if ($stock < 0) {
            throw new Exception('invalid stock: '.$stock);
        }
        
        $api = "/inventory/v1/fs/{$this->_option['fs_id']}/stock/update?shop_id={$this->_option['shop_id']}";
        $param = array(
            ['product_id' => intval($sku['sku_id']), 'new_stock' => $stock],
        );
        try {
//            echo 'tokopedia set stock: ', print_r($param, true), PHP_EOL; return;
            $resp = $this->_client->call($api, $param);
            $resp = json_decode($resp, true);
//            print_r($resp);
            return $resp;
        } catch (Exception $e) {
            throw new Exception('update tokopedia sku stock failed: '.$e->getMessage());
        }
    }
}